<?php

namespace app\service;

use Swoole\Client;
use think\facade\Db;
use think\facade\Log;

class deviceService
{
    public function getList($page,$where){
        return Db::name('device')->where($where)->order('id asc')->paginate(50, false, [
            'page'  =>  $page,
            'query' =>  $where
        ]);
    }
    public function getInfo($id){
        return Db::name('device')->where("id",$id)->find();
    }
    public function getQrcodeInfo($id){
        return Db::name('device')->where("qrcode_id",$id)->find();
    }
    //查询物业条数
    public function number($where){
        return Db::name('device')->where($where)->count();
    }
    //添加物业
    public function add($data){
        return Db::name('device')->insert($data);
    }

    public function edit($data){
        return Db::name('device')->update($data);
    }
    public function open($id){
        $deviceInfo=$this->getQrcodeInfo($id);
        if(empty($deviceInfo)){
            return "设备信息不存在";
        }
        $clientInfo=Db::table("device_client_login")->where("imei",$deviceInfo["imei"])->find();
        if(empty($clientInfo)){
            return "模组信息配置错误或不在线";
        }
        //开闸
        $client=new Client(SWOOLE_SOCK_TCP);
        if ($client->connect("127.0.0.1",9500)) {
            $open["fd"]=$clientInfo["fd"];
            $open["command"]="open";
            //$open["command"]='{"cmd":"onoff1"}';
            $open["imei"]=$clientInfo["imei"];
            $client->send(json_encode($open)); // 发送数据到服务器
            $response = $client->recv(); // 接收服务器响应数据
            Log::record('Received from server: ' . $response); // 记录日志或返回给用户等操作...
            $client->close(); // 关闭连接
            //echo $response."\r\n";
            return "success";
        } else {
            Log::record('Failed to connect to the server.'); // 连接失败处理...
            return "开闸失败";
        }
    }

}